package com.atguigu.utils;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {

    public static JSONObject getDimInfo(Connection connection, String table, String key) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {

        //先查询Redis
        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "DIM:" + table + ":" + key;
        String jsonStr = jedis.get(redisKey);
        if (jsonStr != null) {
            //重置过期时间
            jedis.expire(redisKey, 24 * 60 * 60);
            jedis.close();
            return JSONObject.parseObject(jsonStr);
        }

        //拼接查询SQL
        String querySql = "select * from " + GmallConfig.HBASE_SCHEMA + "." + table + " where id = '" + key + "'";
        System.out.println(querySql);

        //查询
        List<JSONObject> jsonObjects = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);

        //将数据同步到Redis
        JSONObject dimInfo = jsonObjects.get(0);
        jedis.set(redisKey, dimInfo.toJSONString());
        //设置过期时间
        jedis.expire(redisKey, 24 * 60 * 60);
        jedis.close();

        //返回结果
        return dimInfo;
    }

    public static void deleteRedisDimInfo(String table, String key) {

        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "DIM:" + table + ":" + key;

        jedis.del(redisKey);

        jedis.close();
    }

    public static void main(String[] args) throws Exception {

        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "13")); //247  251  271  277  263  260

        long start = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "13")); //9 9   1 2 2 1 2
        long end = System.currentTimeMillis();

        System.out.println(end - start);

        connection.close();
    }

}
